package com.ruoyi.business.controller;

import com.ruoyi.common.constant.ClassesConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.system.domain.SysClasses;
import com.ruoyi.system.domain.SysDataProperty;
import com.ruoyi.system.domain.SysObjectProperty;
import com.ruoyi.system.domain.vo.R;
import com.ruoyi.system.protocol.IDynamicCacheService;
import com.ruoyi.system.protocol.IDynamicDataCommonService;
import com.ruoyi.system.protocol.IDynamicDataService;
import com.ruoyi.system.service.ISysClassesService;
import com.ruoyi.system.service.ISysObjectPropertyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Security;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("ownApi")
public class RedisController {

    @Autowired
    private IDynamicDataService dynamicDataService;

    @Autowired
    private IDynamicDataCommonService dynamicDataCommonService;

    @Autowired
    private IDynamicCacheService dynamicCacheService;

    @Autowired
    private ISysObjectPropertyService sysObjectPropertyService;


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysClassesService sysClassesService;

    private IdWorker idWorker = new IdWorker(2);

    @RequestMapping("/refreshSingle")
    public R refreshSingle() {
        String classesId = ServletUtils.getParameter("classesId");
        SysClasses sysClasses = sysClassesService.selectSysClassesById(Long.parseLong(classesId));
        String classesEn = sysClasses.getNameEn();
        String id = ServletUtils.getParameter("id");
        Map<String, Object> dynamicData = dynamicDataService.findDynamicData(classesEn, null, id);

        getOpDynamic(classesId, classesEn, id, dynamicData);

        redisCache.setCacheMapValue(classesEn+"Cache", id, dynamicData);
        return R.success();
    }

    //获取关联属性
    private void getOpDynamic(String classesId, String classesEn, String id, Map<String, Object> dynamicData) {
        SysObjectProperty sysObjectProperty = new SysObjectProperty();
        sysObjectProperty.setClassesId(Long.parseLong(classesId));
        List<SysObjectProperty> objectPropertyList = sysObjectPropertyService.selectSysObjectPropertyList(sysObjectProperty);
        SysClasses targetClasses = null;
        List<SysDataProperty> dataPropertyListCache = null;
        Map<String, Object> condition = null;
        List<Map<String, Object>> dynamicOpData = null;
        List<Map<String, Object>> ObjectPropertypDataList = null;
        String[] relevanceClassFieldsArr = null;
        SysDataProperty sysDataProperty = null;
        for (SysObjectProperty objectProperty : objectPropertyList) {
            targetClasses = dynamicCacheService.findClassesByCache(objectProperty.getRelevanceClassesId());
            dataPropertyListCache = dynamicCacheService.getDataPropertyListCache(targetClasses.getId() + "");
            List<String> opSelectFields = new ArrayList<>();
            condition = new HashMap<>();
            condition.put("=,source_data_id", id);
            String tableName = ClassesConstants.RESOURCE_TABLE_PREFIX+ classesEn +"_"+objectProperty.getField();
            ObjectPropertypDataList = dynamicDataCommonService.getDynamicData(tableName, null, condition, null, 1, Integer.MAX_VALUE);
            if(ObjectPropertypDataList.size() > 0){
                String relevanceClassFields = objectProperty.getRelevanceClassFields();
                relevanceClassFieldsArr = relevanceClassFields.split(",");
                for (String dataPropertyId : relevanceClassFieldsArr) {
                    sysDataProperty = dataPropertyListCache.stream().filter(x -> (x.getId() + "").equals(dataPropertyId)).findFirst().orElse(null);
                    if(sysDataProperty != null){
                        opSelectFields.add(sysDataProperty.getNameEn());
                    }
                }
                condition = new HashMap<>();
                condition.put("in,id", ObjectPropertypDataList.stream().map(x -> x.get("target_data_id") + "").collect(Collectors.toList()));
                dynamicOpData = dynamicDataCommonService.getDynamicData(ClassesConstants.RESOURCE_TABLE_PREFIX+targetClasses.getNameEn(), opSelectFields, condition, null, 1, ObjectPropertypDataList.size());
                if(dynamicOpData.size() > 0){
                    dynamicData.put(objectProperty.getField(), dynamicOpData);
                }
            }
        }
    }


    @RequestMapping("/refreshAll")
    public R refreshAll() {
        String classesId = ServletUtils.getParameter("classesId");
        SysClasses sysClasses = sysClassesService.selectSysClassesById(Long.parseLong(classesId));
        String classesEn = sysClasses.getNameEn();
        Long dynamicDataCount = dynamicDataService.getDynamicDataCount(classesEn, null);
        List<Map<String, Object>> dynamicData = dynamicDataService.getDynamicData(classesEn, null, null, null, 1, dynamicDataCount.intValue());
        Map<String, Object> cacheMap = new HashMap<>();
        for (Map<String, Object> datum : dynamicData) {
            String id = datum.get("id") + "";
            getOpDynamic(classesId, classesEn, id, datum);
            cacheMap.put(id, datum);
        }
        redisCache.deleteObject(classesEn+"Cache");
        redisCache.setCacheMap(classesEn+"Cache", cacheMap);
        return R.success();
    }


    @RequestMapping("/copyOne")
    public R copyOne() {
        String id = ServletUtils.getParameter("id");
        String classesId = ServletUtils.getParameter("classesId");
        SysClasses sysClasses = sysClassesService.selectSysClassesById(Long.parseLong(classesId));
        String classesEn = sysClasses.getNameEn();
        Map<String, Object> dynamicData = dynamicDataService.findDynamicData(classesEn, null, id);
        String newid = idWorker.nextId() + "";
        dynamicData.put("id", newid);
        String macroAddress = dynamicData.get("macro_address") + "";
        if(StringUtils.isNotBlank(macroAddress) && !"null".equals(macroAddress)){
            macroAddress = macroAddress.replaceAll(id, newid);
            dynamicData.put("macro_address", macroAddress);
        }
        dynamicData.put("create_time", DateUtils.getTime());
        dynamicData.put("update_time", DateUtils.getTime());
        dynamicDataService.addDynamicData(classesEn, dynamicData);
        return R.success();
    }


}
